import React, { useEffect, useState, useRef } from 'react'
import { Card, Input, Button, Space, Select, message, Spin, Badge, Tooltip, Modal, Drawer } from 'antd'
import { 
  SaveOutlined, 
  SendOutlined, 
  SettingOutlined, 
  ReloadOutlined, 
  CheckCircleOutlined, 
  ExclamationCircleOutlined, 
  QuestionCircleOutlined,
  EditOutlined,
  BookOutlined,
  ExperimentOutlined,
  BarChartOutlined,
  ThunderboltOutlined
} from '@ant-design/icons'
import { useModelConfigStore } from '../../stores/model-config.store'
import { usePromptStore } from '../../stores/prompt.store'
import PromptSelector from '../../components/conversation/PromptSelector'
import PromptEditor from '../../components/conversation/PromptEditor'
import PromptLibrary from '../../components/conversation/PromptLibrary'
import PromptTester from '../../components/conversation/PromptTester'
import PromptStatistics from '../../components/conversation/PromptStatistics'
import { Link } from 'react-router-dom'

// 导入新的热点创作编辑器组件
import HotCreatorEditor from './HotCreatorEditor'

const { TextArea } = Input
const { Option } = Select

// 保留原始编辑器作为备份（可选）
const LegacyEditor: React.FC = () => {
  const [selectedModel, setSelectedModel] = useState<string>('')
  const { configs, loading, loadConfigs } = useModelConfigStore()
  const [refreshing, setRefreshing] = useState(false)
  const autoRefreshTimer = useRef<NodeJS.Timeout>()
  
  // 初始加载配置
  useEffect(() => {
    loadConfigs()
  }, [loadConfigs])

  // 设置自动刷新机制（每30秒刷新一次，获取最新的模型状态）
  useEffect(() => {
    const startAutoRefresh = () => {
      autoRefreshTimer.current = setInterval(() => {
        loadConfigs()
      }, 30000) // 30秒自动刷新
    }

    startAutoRefresh()

    return () => {
      if (autoRefreshTimer.current) {
        clearInterval(autoRefreshTimer.current)
      }
    }
  }, [loadConfigs])

  // 监听页面可见性变化，当页面重新可见时立即刷新
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'visible') {
        loadConfigs()
      }
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)
    
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [loadConfigs])

  // 手动刷新模型列表
  const handleRefreshModels = async () => {
    setRefreshing(true)
    try {
      await loadConfigs()
      message.success('模型列表已刷新')
    } catch (error) {
      message.error('刷新失败')
    } finally {
      setRefreshing(false)
    }
  }

  // 获取可用的激活模型（包括unknown状态）
  const availableModels = configs.filter(c => c.isActive === true)
  
  // 分类模型以便在下拉框中分组显示
  const healthyModels = availableModels.filter(c => c.status === 'healthy')
  const unknownModels = availableModels.filter(c => c.status === 'unknown')
  const unhealthyModels = availableModels.filter(c => c.status === 'unhealthy')
  const needTestCount = unknownModels.length

  // 获取模型状态图标
  const getModelStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />
      case 'unhealthy':
        return <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />
      case 'unknown':
        return <QuestionCircleOutlined style={{ color: '#faad14' }} />
      default:
        return null
    }
  }

  // 获取状态描述
  const getStatusDescription = (status: string, lastChecked?: Date) => {
    const timeStr = lastChecked ? `最后检测: ${new Date(lastChecked).toLocaleString()}` : '未检测'
    switch (status) {
      case 'healthy':
        return `正常 - ${timeStr}`
      case 'unhealthy':
        return `异常 - ${timeStr}`
      case 'unknown':
        return `未知 - 建议点击"测试模型"进行检测`
      default:
        return status
    }
  }
  
  // 监听store配置变化，当有配置更新时立即刷新
  useEffect(() => {
    // 监听配置数组长度或状态变化
    const handleStoreUpdate = () => {
      // 如果当前选中的模型状态发生变化，给出提示
      if (selectedModel) {
        const currentModel = configs.find(c => c.id === selectedModel)
        if (currentModel && currentModel.status === 'healthy') {
          console.log(`[EDITOR] 模型 ${currentModel.displayName || currentModel.modelName} 状态已更新为健康`)
        }
      }
    }
    
    // 当configs数组发生变化时触发
    handleStoreUpdate()
  }, [configs, selectedModel])
  useEffect(() => {
    if (!selectedModel && availableModels.length > 0) {
      setSelectedModel(availableModels[0].id)
    }
  }, [availableModels, selectedModel])

  const handleModelChange = (value: string) => {
    setSelectedModel(value)
    const model = configs.find(c => c.id === value)
    if (model) {
      message.info(`已切换到模型: ${model.displayName || model.modelName}`)
    }
  }

  return (
    <div className="h-full">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold">AI创作编辑器</h1>
        <Space>
          {loading || refreshing ? (
            <Spin size="small" />
          ) : (
            <>
              <Tooltip title="刷新模型列表">
                <Button 
                  icon={<ReloadOutlined />} 
                  size="small" 
                  loading={refreshing}
                  onClick={handleRefreshModels}
                />
              </Tooltip>
              <Select
                value={selectedModel}
                onChange={handleModelChange}
                style={{ width: 280 }}
                placeholder="选择AI模型"
                notFoundContent={
                  <div style={{ padding: '8px', textAlign: 'center' }}>
                    <p>暂无可用模型</p>
                    <Link to="/model-config">
                      <Button type="link" icon={<SettingOutlined />} size="small">
                        前往配置
                      </Button>
                    </Link>
                  </div>
                }
                optionLabelProp="label"
              >
                {healthyModels.length > 0 && (
                  <Select.OptGroup label="健康模型">
                    {healthyModels.map(config => (
                      <Option 
                        key={config.id} 
                        value={config.id}
                        label={
                          <span>
                            {getModelStatusIcon(config.status)}
                            {' '}
                            {config.displayName || config.modelName}
                          </span>
                        }
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span>
                            {getModelStatusIcon(config.status)}
                            {' '}
                            {config.displayName || config.modelName}
                            {config.providerName && (
                              <span style={{ color: '#8c8c8c', fontSize: '12px', marginLeft: '8px' }}>
                                ({config.providerName})
                              </span>
                            )}
                          </span>
                          <Badge status="success" />
                        </div>
                        <div style={{ fontSize: '12px', color: '#8c8c8c', marginTop: '2px' }}>
                          {getStatusDescription(config.status, config.lastChecked)}
                        </div>
                      </Option>
                    ))}
                  </Select.OptGroup>
                )}
                
                {unknownModels.length > 0 && (
                  <Select.OptGroup label={`未检测模型 (${needTestCount}个)`}>
                    {unknownModels.map(config => (
                      <Option 
                        key={config.id} 
                        value={config.id}
                        label={
                          <span>
                            {getModelStatusIcon(config.status)}
                            {' '}
                            {config.displayName || config.modelName}
                          </span>
                        }
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span>
                            {getModelStatusIcon(config.status)}
                            {' '}
                            {config.displayName || config.modelName}
                            {config.providerName && (
                              <span style={{ color: '#8c8c8c', fontSize: '12px', marginLeft: '8px' }}>
                                ({config.providerName})
                              </span>
                            )}
                          </span>
                          <Badge status="warning" />
                        </div>
                        <div style={{ fontSize: '12px', color: '#8c8c8c', marginTop: '2px' }}>
                          {getStatusDescription(config.status, config.lastChecked)}
                        </div>
                      </Option>
                    ))}
                  </Select.OptGroup>
                )}

                {unhealthyModels.length > 0 && (
                  <Select.OptGroup label="异常模型">
                    {unhealthyModels.map(config => (
                      <Option 
                        key={config.id} 
                        value={config.id}
                        label={
                          <span>
                            {getModelStatusIcon(config.status)}
                            {' '}
                            {config.displayName || config.modelName}
                          </span>
                        }
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span>
                            {getModelStatusIcon(config.status)}
                            {' '}
                            {config.displayName || config.modelName}
                            {config.providerName && (
                              <span style={{ color: '#8c8c8c', fontSize: '12px', marginLeft: '8px' }}>
                                ({config.providerName})
                              </span>
                            )}
                          </span>
                          <Badge status="error" />
                        </div>
                        <div style={{ fontSize: '12px', color: '#8c8c8c', marginTop: '2px' }}>
                          {getStatusDescription(config.status, config.lastChecked)}
                        </div>
                      </Option>
                    ))}
                  </Select.OptGroup>
                )}
              </Select>
              {availableModels.length === 0 && (
                <Link to="/model-config">
                  <Button type="dashed" icon={<SettingOutlined />} size="small">
                    配置模型
                  </Button>
                </Link>
              )}
              {needTestCount > 0 && (
                <Link to="/model-config">
                  <Tooltip title={`有${needTestCount}个模型需要测试连接`}>
                    <Button 
                      type="dashed" 
                      icon={<SettingOutlined />} 
                      size="small"
                      style={{ color: '#faad14', borderColor: '#faad14' }}
                    >
                      测试模型 ({needTestCount})
                    </Button>
                  </Tooltip>
                </Link>
              )}
            </>
          )}
          <Button icon={<SaveOutlined />}>保存</Button>
        </Space>
      </div>

      <Card className="h-full">
        <div className="mb-4">
          <Input
            placeholder="输入文章标题..."
            className="text-lg font-semibold"
            size="large"
          />
        </div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 h-96">
          <div>
            <div className="mb-2 font-semibold text-gray-700">输入区</div>
            <TextArea
              placeholder="在这里输入您的提示词或初始内容..."
              className="h-full resize-none"
            />
          </div>
          
          <div>
            <div className="mb-2 font-semibold text-gray-700">生成内容</div>
            <div className="border rounded-lg p-4 h-full bg-gray-50 overflow-auto">
              <p className="text-gray-500">AI生成的内容将显示在这里...</p>
            </div>
          </div>
        </div>

        <div className="mt-4 flex justify-end">
          <Button type="primary" icon={<SendOutlined />} size="large">
            开始生成
          </Button>
        </div>
      </Card>
    </div>
  )
}

// 使用新的热点创作编辑器作为默认导出
const EditorPage = HotCreatorEditor

export default EditorPage